<template>
  <div class="announcements-container">
    <div class="header-section">
      <div class="title-area">
        <h1 class="page-title">公告中心</h1>
      </div>
      <div class="search-area">
        <el-input v-model="searchKeyword" placeholder="搜索公告..." class="search-input" clearable :prefix-icon="Search" @input="handleSearch" />
      </div>
    </div>

    <div v-loading="loading" class="announcement-board">
      <div v-if="filteredAnnouncements.length === 0" class="empty-container">
        <el-empty description="暂无公告" />
      </div>

      <div v-else>
        <div class="announcement-list">
          <div v-for="item in paginatedAnnouncements" :key="item.id" class="announcement-card" @click="viewAnnouncementDetail(item.id)">
            <div class="announcement-tag" :class="getAnnouncementTagClass(item)">
              {{ getAnnouncementTagText(item) }}
            </div>
            <div class="card-content">
              <div class="card-date">{{ formatDate(item.publishTime) }}</div>
              <h3 class="announcement-title">{{ item.title }}</h3>
              <p class="announcement-preview">{{ formatContent(item.content) }}</p>
            </div>
            <div class="card-footer">
              <div class="publisher">
                <el-avatar :size="24" :icon="User" :src="item.publisherAvatar" class="publisher-avatar" />
                <span class="publisher-name">{{ item.publisherName }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[5, 10, 20, 30]" :total="filteredAnnouncements.length" @current-change="handlePageChange" @size-change="handleSizeChange" :pager-count="5" background />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, User } from '@element-plus/icons-vue'
import { getAnnouncements } from '@/api/announcement'

const router = useRouter()
const announcements = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)  // 每页显示10条

// 计算属性：过滤后的公告列表
const filteredAnnouncements = computed(() => {
  if (!searchKeyword.value) {
    return announcements.value
  }
  return announcements.value.filter(item =>
    item.title.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 计算属性：当前页的公告
const paginatedAnnouncements = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAnnouncements.value.slice(start, end)
})

// 查询公告列表
const fetchAnnouncements = async () => {
  loading.value = true
  try {
    const res = await getAnnouncements()
    announcements.value = res.data.sort((a, b) => {
      // 按照发布时间降序排序，最新的排在前面
      return new Date(b.publishTime) - new Date(a.publishTime)
    })
  } catch (error) {
    ElMessage.error('获取公告列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
  // 回到页面顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 处理每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size
  // 重置到第一页
  currentPage.value = 1
  // 回到页面顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

// 获取公告标签类名
const getAnnouncementTagClass = (announcement) => {
  // 这里根据公告的属性或日期来确定标签类型
  const publishDate = new Date(announcement.publishTime)
  const now = new Date()
  const diffDays = Math.floor((now - publishDate) / (1000 * 60 * 60 * 24))

  if (diffDays < 3) return 'tag-new' // 最近3天发布的
  if (diffDays < 7) return 'tag-recent' // 最近一周发布的
  return 'tag-normal' // 一周前发布的
}

// 获取公告标签文本
const getAnnouncementTagText = (announcement) => {
  const tagClass = getAnnouncementTagClass(announcement)
  switch (tagClass) {
    case 'tag-new': return '新'
    case 'tag-recent': return '近期'
    default: return '公告'
  }
}

// 格式化内容（截取部分显示）
const formatContent = (content) => {
  if (!content) return ''
  // 移除HTML标签，只保留纯文本
  const plainText = content.replace(/<[^>]+>/g, '')
  return plainText.length > 50 ? plainText.substring(0, 50) + '...' : plainText
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  })
}

// 查看公告详情
const viewAnnouncementDetail = (id) => {
  router.push(`/student/announcement/${id}`)
}

// 监听搜索关键词变化，重置页码
const handleSearch = () => {
  currentPage.value = 1
}

// 监听过滤后的公告列表变化，确保当前页有数据
watch(filteredAnnouncements, (newVal) => {
  if (newVal.length > 0) {
    const maxPage = Math.ceil(newVal.length / pageSize.value)
    if (currentPage.value > maxPage) {
      currentPage.value = maxPage
    }
  }
})

// 初始化
onMounted(() => {
  fetchAnnouncements()
})
</script>

<style scoped>
.announcements-container {
  padding: 30px;
  min-height: 100vh;
  background-color: #f9fafc;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.title-area {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.title-desc {
  font-size: 14px;
  color: #606266;
}

.search-area {
  min-width: 280px;
}

.search-input {
  border-radius: 8px;
}

.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  background-color: #fff;
  padding: 8px 12px;
  border: 1px solid #bae6fd;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: #0ea5e9;
}

.announcement-board {
  position: relative;
  min-height: 200px;
}

.empty-container {
  padding: 40px 0;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}

.announcement-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
  gap: 16px;
}

.announcement-card {
  cursor: pointer;
  position: relative;
  padding: 18px;
  border-radius: 12px;
  background: linear-gradient(145deg, #ffffff, #f9f7ff);
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05), 0 1px 2px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  display: flex;
  flex-direction: column;
  height: 190px;
  overflow: hidden;
  border: 1px solid rgba(214, 207, 253, 0.3);
}

.announcement-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(to right, #409EFF, #66b1ff);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.announcement-card:hover {
  box-shadow: 0 12px 20px -5px rgba(64, 158, 255, 0.15), 0 8px 16px -8px rgba(64, 158, 255, 0.15);
  transform: translateY(-4px);
  border-color: rgba(64, 158, 255, 0.3);
  background: linear-gradient(145deg, #ffffff, #f0f7ff);
}

.announcement-card:hover::before {
  opacity: 1;
}

.announcement-card:active {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px -3px rgba(99, 102, 241, 0.2);
}

.announcement-tag {
  position: absolute;
  top: 0;
  right: 0;
  padding: 4px 10px;
  font-size: 12px;
  font-weight: 600;
  border-radius: 0 12px 0 12px;
  color: #fff;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  letter-spacing: 0.5px;
}

.tag-new {
  background: linear-gradient(135deg, #409EFF, #337ecc);
}

.tag-recent {
  background: linear-gradient(135deg, #66b1ff, #409EFF);
}

.tag-normal {
  background: linear-gradient(135deg, #9ca3af, #6b7280);
}

.card-content {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  padding: 0;
}

.card-date {
  position: relative;
  font-size: 13px;
  color: #6b7280;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  padding-left: 5px;
  font-weight: 500;
}

.card-date::before {
  content: '';
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #409EFF;
  border-radius: 50%;
  margin-right: 8px;
}

.announcement-card:hover .card-date::before {
  background-color: #337ecc;
}

.announcement-title {
  font-size: 17px;
  font-weight: 600;
  color: #111827;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  position: relative;
  padding-bottom: 5px;
}

.announcement-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 40px;
  height: 2px;
  background-color: #e5e7eb;
  transition: width 0.3s ease, background-color 0.3s ease;
}

.announcement-card:hover .announcement-title::after {
  width: 80px;
  background-color: #409EFF;
}

.announcement-preview {
  font-size: 13px;
  color: #4b5563;
  line-height: 1.5;
  margin: 0 0 12px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex-grow: 1;
  position: relative;
  padding-left: 1px;
}

.card-footer {
  display: flex;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #e5e7eb;
  margin-top: auto;
  position: relative;
}

.card-footer::after {
  display: none;
}

.publisher {
  display: flex;
  align-items: center;
  gap: 8px;
  background-color: rgba(243, 244, 246, 0.7);
  border-radius: 20px;
  padding: 4px 12px 4px 4px;
  transition: all 0.3s ease;
}

.announcement-card:hover .publisher {
  background-color: rgba(235, 245, 255, 0.7);
}

.publisher-avatar {
  background-color: #ecf5ff;
  border: 1px solid #b3d8ff;
  transition: transform 0.3s ease;
}

.announcement-card:hover .publisher-avatar {
  transform: scale(1.1);
}

.publisher-name {
  font-size: 13px;
  color: #4b5563;
  font-weight: 500;
  transition: color 0.3s ease;
}

.announcement-card:hover .publisher-name {
  color: #409EFF;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 40px;
  margin-bottom: 30px;
  position: relative;
}

.pagination-container::before {
  display: none;
  /* 移除装饰线条 */
}

.pagination-container :deep(.el-pagination) {
  --el-pagination-bg-color: #fff;
  --el-pagination-hover-color: #409EFF;
  --el-pagination-button-color: #475569;
  padding: 14px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
  background: #ffffff;
  font-weight: 500;
  border: 1px solid #ebeef5;
}

.pagination-container :deep(.el-pagination.is-background .el-pager li) {
  margin: 0 3px;
  min-width: 32px;
  border-radius: 4px;
  transition: all 0.2s;
  font-weight: 500;
  color: #606266;
}

.pagination-container :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409EFF;
  box-shadow: 0 2px 5px rgba(64, 158, 255, 0.25);
  font-weight: 600;
}

.pagination-container :deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #409EFF;
  transform: none;
  box-shadow: none;
  background-color: #f0f7ff;
}

.pagination-container :deep(.el-pagination .btn-prev),
.pagination-container :deep(.el-pagination .btn-next) {
  border-radius: 4px;
  background-color: #fff;
  border: 1px solid #ebeef5;
  color: #606266;
}

.pagination-container :deep(.el-pagination .btn-prev:hover),
.pagination-container :deep(.el-pagination .btn-next:hover) {
  color: #409EFF;
  border-color: #d6e8ff;
  background-color: #f0f7ff;
}

@media (max-width: 768px) {
  .announcements-container {
    padding: 20px;
  }

  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .search-area {
    width: 100%;
  }

  .announcement-list {
    grid-template-columns: 1fr;
  }

  .announcement-card {
    height: auto;
    min-height: 180px;
  }

  .pagination-container {
    margin-top: 30px;
    justify-content: center;
  }

  .pagination-container :deep(.el-pagination) {
    padding: 10px 14px;
    flex-wrap: wrap;
    justify-content: center;
    gap: 10px;
    width: 100%;
    max-width: 440px;
  }
}
</style>